<?php
namespace app;

use app\model\MyException;
use app\model\table\user\User;
use think\App;
use think\facade\Request;

/**
 * 需要登录的controller
 * Class VerifyController
 * @package app
 */
class  LoginController extends MyController
{
    private $not_need_cheek_token_action = ['getTokenAction'];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->token = Request::instance()->header('token') != "" ? Request::instance()->header('token') : $this->request->get('token');
        $this->checkToken();
    }

    /**
     * 解析token,并检测token相关信息是否正确
     * @return mixed
     */
    public function checkToken()
    {
        try {
            // 只有开启了json验证才做下面操作
            $nowAction = Request()->action();
            if(!in_array($nowAction, $this->not_need_cheek_token_action)){
                $token = $this->token;
                if(empty($token)){
                    throw new MyException("token不正确");
                }

                $UserObj = User::instance()->findOne(['token'=>$token]);
                if(empty($UserObj)){
                    throw new MyException("用户不存在");
                }
                $this->setUser($UserObj);
            }
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }
}